#!/bin/bash
# common functions of reload tests

exit_with_error() {
  echo "$1"
  estat=1
  end_test
  exit 1
}

stop_director() {
  "${rscripts}/susan-ctl-dir" stop
}

start_director() {
  "${rscripts}/susan-ctl-dir" start "$director_debug_level"
  case $(uname -s) in
    SunOS)
      director_pid=$(pgrep -f ${SUSAN_DIRECTOR_BINARY})
      ;;
    *)
      director_pid=$(pidof ${SUSAN_DIRECTOR_BINARY});;
  esac

  if [ -z "$director_pid" ]; then
    exit_with_error "Susan director could not be started"
  fi
}

create_console_command_file() {
  if [ ! -f "$bconsole_command_file" ]; then
  cat > "$bconsole_command_file" <<EOF
@$out "$console_logfile"
reload
messages
EOF
  fi
}

test_reload_will_not_crash_director() {
  create_console_command_file

  if  ! "${SUSAN_BCONSOLE_BINARY}" -c "$conf"/bconsole.conf < "$bconsole_command_file" 2>&1 >> /dev/null
  then
    exit_with_error "BConsole finished with errors"
  fi

  if  ! "${SUSAN_BCONSOLE_BINARY}" -c "$conf"/bconsole.conf < "$bconsole_command_file" 2>&1 >> /dev/null
  then
    exit_with_error "Susan Director seems to have crashed after reload"
  fi
}

remove_console_logfiles() {
  rm -f "$console_logfile"
  rm -f "$console_show_client_output_file"
}

remove_console_logfile() {
  rm -f "$console_logfile"
}

find_added_client_in_config() {
  echo "show client" | "${SUSAN_BCONSOLE_BINARY}" -c "$conf"/bconsole.conf > "$console_show_client_output_file"
  if ! grep -wq "susan-fd-2" "$console_show_client_output_file"; then
    exit_with_error 'Could not find client "susan-fd-2" in console output'
  fi
}

add_another_client() {
cat <<END_OF_DATA > "$temporary_config_file"
Client {
  Name = susan-fd-2
  Description = "Another Client resource."
  Address = localhost
  Password = "@fd_password@"          # password for FileDaemon
  FD PORT = @fd_port@
}
END_OF_DATA
}

find_error_string_in_console_log() {
  local err
  err="$1"
  if ! grep -q "$err" "$console_logfile"; then
    exit_with_error "Could not find error string in console output"
  fi
}

add_duplicate_job_to_config() {
cat <<END_OF_DATA2 > "$temporary_job_config_file"
Job {
  Name = "backup-susan-fd"
  JobDefs = "DefaultJob"
  Client = "susan-fd"
}
END_OF_DATA2
}

add_empty_job_to_config() {
cat <<END_OF_DATA3 > "$temporary_job_config_file"
Job {
}
END_OF_DATA3
}

add_duplicate_dir_to_config() {
cat <<END_OF_DATA4 > "$temporary_director_config_file"
Director {                            # define myself
  Name = susan-dir-2
  QueryFile = "@scriptdir@/query.sql"
  Maximum Concurrent Jobs = 10
  Password = "@dir_password@"         # Console password
  Messages = Daemon
  Auditing = yes
#  Backend Directory = @backenddir@
  Working Directory =  "@working_dir@"
  Pid Directory =  "@piddir@"
  DirPort = @dir_port@
}
END_OF_DATA4
}

add_uncommented_string_to_config() {
cat <<END_OF_DATA5 > "$temporary_config_file"
This is an uncommented string that causes a config abort.
END_OF_DATA5
}
